package service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import model.command.Command;
import model.command.RmCommand;
import model.command.SetCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import utils.CommandUtil;
import utils.LoggerUtil;
import utils.RandomAccessFileUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;

public class Deduplicate {

    private static final Logger LOGGER = LoggerFactory.getLogger(Deduplicate.class);
    private static final String logFormat = "[DataDeduplicate][{}]: {}";

    /**
     * 对文件中的数据进行去重，保留每个key的最新value。
     *
     * @param filePath 文件路径
     * @throws IOException 如果文件操作发生错误
     */
    public static void deduplicateData(String filePath) throws IOException {
        File file = new File(filePath);
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            // 使用LinkedHashMap来保持插入顺序
            Map<String, String> keyValueMap = new LinkedHashMap<>();

            String line;
            while ((line = reader.readLine()) != null) {
                JSONObject jsonObject = JSON.parseObject(line);
                String key = jsonObject.getString("key");
                if ("SET".equals(jsonObject.getString("type"))) {
                    String value = jsonObject.getString("value");
                    keyValueMap.put(key, value);
                }
            }
            // 写入去重后的数据到新文件
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                for (Map.Entry<String, String> entry : keyValueMap.entrySet()) {
                    JSONObject newJsonObject = new JSONObject();
                    newJsonObject.put("key", entry.getKey());
                    newJsonObject.put("type", "SET");
                    newJsonObject.put("value", entry.getValue());
                    String newLine = newJsonObject.toJSONString() + "\n";
                    writer.write(newLine);
                    LOGGER.info(logFormat, "Written new data entry: " + newLine);
                }
            }
        }
    }

}